package com.kpx.app.utils;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.amap.api.location.AMapLocation;
import com.kpx.app.R;
import com.kpx.app.activity.ActivityLogin;
import com.kpx.app.activity.ActivityUserInfo;
import com.kpx.app.base.ActivityBase;
import com.kpx.app.base.FragmentBase;
import com.kpx.app.bean.AddressBean;
import com.kpx.app.bean.ContactInfoBean;
import com.kpx.app.bean.LocationDetails;
import com.kpx.app.bean.LoginUser;
import com.kpx.app.bean.MenuBean;
import com.kpx.app.bean.RegionNew;
import com.kpx.app.bean.User;
import com.kpx.app.bean.Wallet;
import com.kpx.app.cache.FileCache;
import com.kpx.app.cache.SQLiteCache;
import com.kpx.app.cache.SecondLevelCache;
import com.kpx.app.configs.Constants;
import com.kpx.app.http.HttpDataApi;
import com.kpx.app.http.HttpDataLoader;
import com.kpx.app.http.HttpDataReqUrl;
import com.kpx.app.http.HttpDataRequest;
import com.kpx.app.http.ResObj;
import com.kpx.app.listener.OnLocationReceivedListener;
import com.kpx.app.thirdparty.JPush.JPushUtils;
import com.kpx.app.thirdparty.amap.LocationGetter;
import com.kpx.app.utils.datautils.FileUtils;
import com.kpx.app.utils.datautils.LogUtils;
import com.kpx.app.utils.dbutils.DBOperateUtils;
import com.kpx.app.utils.dbutils.SpUtil;
import com.kpx.app.utils.uiutils.ToastUtil;

import java.util.ArrayList;

/**
 * User: 陈聪(617909447@qq.com)
 * Date: 2016-06-28
 * Time: 10:54
 * 用于获取用户的相关信息
 */
public class UserInfoUtils {
    /**
     * 登录返回-返回进入页面
     */
    public static final int BACK_TO_FROM = 100;
    /**
     * 登录返回-返回首页
     */
    public static final int BACK_TO_MAIN = 0;
    private static LocationGetter locationGetter;
    private static String TAG = "UserInfoUtils";

    public interface OnGetSellerInfoBackListener {
        void back(ContactInfoBean bean);
    }

    /**
     * 获取信息
     *
     * @param context
     * @param listener
     */
    public static void getSellerInfo(final Context context, final OnGetSellerInfoBackListener listener) {
        new HttpDataLoader(new HttpDataApi.OnRequestCallback() {
            @Override
            public void onRequestSuccess(String url, ResObj result, boolean isFrmCache) {
                if (result.getCode() == 0) {
                    listener.back((ContactInfoBean) result.getData());
                    FileCache.sharedInstance().put(Constants.KEY_SELLER_BEAN, result.getData());
                } else {
                    ContactInfoBean bean = (ContactInfoBean) FileCache.sharedInstance().get(Constants.KEY_SELLER_BEAN);
                    listener.back(bean);
                    ToastUtil.getInstance().showToast(context, result.getMsg());
                }
            }

            @Override
            public void onRequestError(String url, int statusCode, String error) {
                ContactInfoBean bean = (ContactInfoBean) FileCache.sharedInstance().get(Constants.KEY_SELLER_BEAN);
                listener.back(bean);
                ToastUtil.getInstance().showToast(context, error);
            }
        }, ContactInfoBean.class, HttpDataRequest.TYPE_OBJECT).POST(HttpDataReqUrl.URL_POST_GET_SELLER_INFO, true, new MyHashMap());
    }

    public interface OnGetCategerysBackListener {
        void back(ArrayList<MenuBean> menus);
    }

    /**
     * 获取任务列表的分类信息
     *
     * @param context
     * @param listener
     */
    public static void getTaskCategerys(final Context context,int type ,final OnGetCategerysBackListener listener) {
//        ArrayList<MenuBean> menus = getCacheTaskCategery();
//        if (menus != null) {
//            listener.back(menus);
//        } else {
        new HttpDataLoader(new HttpDataApi.OnRequestCallback() {
            @Override
            public void onRequestSuccess(String url, ResObj result, boolean isFrmCache) {
                if (result.getCode() == 0) {
                    listener.back((ArrayList<MenuBean>) result.getData());
                    FileCache.sharedInstance().put(Constants.KEY_CATEGERYS_LIST, result.getData());
                } else {
                    listener.back(getCacheTaskCategery());
                    ToastUtil.getInstance().showToast(context, result.getMsg());
                }
            }

            @Override
            public void onRequestError(String url, int statusCode, String error) {
                listener.back(getCacheTaskCategery());
                ToastUtil.getInstance().showToast(context, error);
            }
        }, MenuBean.class, HttpDataRequest.TYPE_LIST).POST(type==1?HttpDataReqUrl.URL_POST_TASK_CATEGERYS:HttpDataReqUrl.URL_POST_TASK_CATEGERYS_main, true, new MyHashMap());
//        }
    }

    private static ArrayList<MenuBean> getCacheTaskCategery() {
        return (ArrayList<MenuBean>) FileCache.sharedInstance().get(Constants.KEY_CATEGERYS_LIST);
    }

    public interface OnGetCodeBackListener {
        void back(boolean s);
    }

    /**
     *
     * @param context
     * @param num
     * @param valid 1注册2重置密码3忘记密码4钱包获取验证码
     * @param listener
     */
    public static void getCode(final Context context, String num, int valid, final OnGetCodeBackListener listener) {
        MyHashMap map = new MyHashMap();
        map.put("phone", num);
        String url ="";
        switch (valid){
            case 1:
                url =HttpDataReqUrl.URL_POST_GETCODE;
                break;
            case 2:
                url =HttpDataReqUrl.URL_POST_GETCODE2;
                break;
            case 3:
                url =HttpDataReqUrl.URL_POST_GETCODE3;
                break;
            case 4:
                url =HttpDataReqUrl.URL_POST_GETCODE4;
                break;
        }
        new HttpDataLoader(new HttpDataApi.OnRequestCallback() {
            @Override
            public void onRequestSuccess(String url, ResObj result, boolean isFrmCache) {
                if (result.getCode() == 0) {
                    listener.back(true);
                } else {
                    listener.back(false);
                    ToastUtil.getInstance().showToast(context, result.getMsg());
                }
            }

            @Override
            public void onRequestError(String url, int statusCode, String error) {
                listener.back(false);
                ToastUtil.getInstance().showToast(context, error);
            }
        }, null, null).POST(url, true, map);

    }

    public interface OnGetMyWalletBackListener {
        void back(Wallet aBeans);
    }

    /**
     * 获取地址信息
     */
    public static void getMyWallet(final Context context, final OnGetMyWalletBackListener listener) {
        new HttpDataLoader(new HttpDataApi.OnRequestCallback() {
            @Override
            public void onRequestSuccess(String url, ResObj result, boolean isFrmCache) {
                if (result.getCode() == 0) {
                    listener.back((Wallet) result.getData());
                    LoginUser loginUser = getCachedLoginUser();
                    if(loginUser!=null){
                        loginUser.setWALLET((Wallet) result.getData());
                        saveLoginUser(loginUser);
                    }
                } else {
                    listener.back(getCachedLoginUser().getWALLET());
                    ToastUtil.getInstance().showToast(context, result.getMsg());
                }
            }

            @Override
            public void onRequestError(String url, int statusCode, String error) {
                listener.back(getCachedLoginUser().getWALLET());
                ToastUtil.getInstance().showToast(context, error);
            }
        }, Wallet.class, HttpDataRequest.TYPE_OBJECT).POST(HttpDataReqUrl.URL_GET_MY_WALLET, true, new MyHashMap());
    }

    public interface OnGetAddressdataBackListener {
        void back(ArrayList<AddressBean> aBeans);
    }

    /**
     * 获取地址信息
     */
    public static void getAddress(final Context context, final OnGetAddressdataBackListener listener) {
        new HttpDataLoader(new HttpDataApi.OnRequestCallback() {
            @Override
            public void onRequestSuccess(String url, ResObj result, boolean isFrmCache) {
                if (result.getCode() == 0) {
                    ArrayList<AddressBean> aBeans = (ArrayList<AddressBean>) result.getData();
                    if (aBeans != null) {
                        FileCache.sharedInstance().put(Constants.KEY_ADDRESS_LIST, aBeans);
                    }
                    listener.back(aBeans);
                } else {
                    listener.back(getCacheAddress());
                    ToastUtil.getInstance().showToast(context, result.getMsg());
                }
            }

            @Override
            public void onRequestError(String url, int statusCode, String error) {
                listener.back(getCacheAddress());
                ToastUtil.getInstance().showToast(context, error);
            }
        }, AddressBean.class, HttpDataRequest.TYPE_LIST).POST(HttpDataReqUrl.URL_GET_ADDRESS_GET_LIST, true, new MyHashMap());
    }

    public static ArrayList<AddressBean> getCacheAddress() {
        return (ArrayList<AddressBean>) FileCache.sharedInstance().get(Constants.KEY_ADDRESS_LIST);
    }

    /**
     * 更新本地用户信息
     *
     * @param updateType
     * @param s
     */
    public static void updateUserInfoCache(int updateType, String s) {
        LoginUser loginUser = getCachedLoginUser();
        if (loginUser != null) {
            User user = loginUser.getUSER();
            if (user != null) {
                switch (updateType) {
                    case ActivityUserInfo.TYPE_NICK://昵称
                        user.setNickName(s);
                        break;
                    case ActivityUserInfo.TYPE_SEX://性别
                        user.setSex(s);
                        break;
                    case ActivityUserInfo.TYPE_LOCATION://地区
                        user.setRegion(s);
                        break;
                    case ActivityUserInfo.TYPE_AGE://年龄
                        user.setAge(s);
                        break;
                    case ActivityUserInfo.TYPE_HEIGHT://身高
                        user.setHeight(s);
                        break;
                    case ActivityUserInfo.TYPE_WEIGHT://体重
                        user.setWeight(s);
                        break;
                    case ActivityUserInfo.TYPE_SHOSE_SIZE://鞋码
                        user.setShoeSize(s);
                        break;
                    case ActivityUserInfo.TYPE_CLOTH_SIZE://衣服尺码
                        user.setClothingSize(s);
                        break;
                    case ActivityUserInfo.TYPE_BWH_X://三围bust(胸围),waist(腰围),cupSize(罩杯)
                        user.setBust(s);
                        break;
                    case ActivityUserInfo.TYPE_BWH_Y://三围
                        user.setWaist(s);
                        break;
                    case ActivityUserInfo.TYPE_BWH_T://三围
                        user.setHips(s);
                        break;
                    case ActivityUserInfo.TYPE_BWH_XZ://三围
                        user.setCupSize(s);
                        break;
                    case ActivityUserInfo.TYPE_LABEL://标签
                        break;
                    case ActivityUserInfo.TYPE_HEADIMG://标签
                        user.setHeadImg(s);
                        break;
                    case ActivityUserInfo.TYPE_ADDRESS://收获地址
                        break;

                }
                saveLoginUser(loginUser);
            }
        }
    }

    public static void updateUserInfoCache(LoginUser loginUser) {
        if (loginUser != null) {
            saveLoginUser(loginUser);
        }
    }

    public interface OnUpdateUserInfoBackListener {
        void back(boolean issuccess, String msg);
    }

    /**
     * 保存用户修改的信息
     * 参数：token,headImg,nickName,sex(1男,2女)
     * ,region(广东省-深圳市),
     * birthDay(1990-05-20),
     * age(26),height(170),
     * weight(70),
     * shoeSize(鞋码42),
     * clothingSize(衣码由基础数据来),
     * bust(胸围),
     * waist(腰围),
     * cupSize(罩杯)
     * 返回：{"code":0}
     */
    public static void toUpdateData(final Context context, MyHashMap map, final OnUpdateUserInfoBackListener listener) {
        new HttpDataLoader(new HttpDataApi.OnRequestCallback() {
            @Override
            public void onRequestSuccess(String url, ResObj result, boolean isFrmCache) {
                if (result.getCode() == 0) {
                    listener.back(true, "");
                } else {
                    listener.back(false, result.getMsg());
                    ToastUtil.getInstance().showToast(context, result.getMsg());
                }
            }

            @Override
            public void onRequestError(String url, int statusCode, String error) {
                listener.back(false, error);
                ToastUtil.getInstance().showToast(context, error);
            }

        }, null, null).POST(HttpDataReqUrl.URL_POST_COMPLETE_INFO, true, map);
    }

    public interface OnGetPCdataBackListener {
        void getData(ArrayList<RegionNew> regions);
    }

    public static void getPCdata(final Context context, final OnGetPCdataBackListener listener) {
        ArrayList<RegionNew> regions1 = (ArrayList<RegionNew>) SQLiteCache.sharedInstance().get(context.getResources().getString(R.string.sql_supermarket_pcdata_bean));
        if (regions1 != null) {
            if (listener != null) {
                listener.getData(regions1);
            }
        } else {
        new HttpDataLoader(new HttpDataApi.OnRequestCallback() {
            @Override
            public void onRequestSuccess(String url, ResObj networkResult, boolean isFrmCache) {
                int resultCode = networkResult.getCode();
                if (resultCode == Constants.CODE_SUCCESS) {
                    ArrayList<RegionNew> regions = (ArrayList<RegionNew>) networkResult.getData();
                    SQLiteCache.sharedInstance().clear(context.getResources().getString(R.string.sql_supermarket_pcdata_bean));
                    SQLiteCache.sharedInstance().put(context.getResources().getString(R.string.sql_supermarket_pcdata_bean), regions);
                    SecondLevelCache.sharedInstance().put(Constants.KEY_REGION_LIST, regions);
                    if (listener != null) {
                        listener.getData(regions);
                    }
                } else {
                    listener.getData(null);

                    ToastUtil.getInstance().showToast(context, networkResult.getMsg());
                }

            }

            @Override
            public void onRequestError(String url, int statusCode, String error) {
                listener.getData(null);
                ToastUtil.getInstance().showToast(context, error);
            }
        }, RegionNew.class, HttpDataRequest.TYPE_LIST).POST(HttpDataReqUrl.URL_POST_GET_REGIONS, true, new MyHashMap());
        }
    }

    /**
     * 获取本地缓存的登录用户对象
     */
    public static LoginUser getCachedLoginUser() {
        String dmid = SpUtil.getString(Constants.KEY_USER_DMID);
        if (TextUtils.isEmpty(dmid)) {
            return null;
        }
        return (LoginUser) SQLiteCache.sharedInstance().get(dmid);
    }

    public static void clearLoginInfo() {
        LoginUser loginUserDefault = null;
        if (getCachedLoginUser() != null && getCachedLoginUser().getUSER() != null) {
            loginUserDefault = new LoginUser();
            User user = new User();
            user.setPhone(getCachedLoginUser().getUSER().getPhone());
            user.setPassword(getCachedLoginUser().getUSER().getPassword());
            loginUserDefault.setUSER(user);
        }
        SecondLevelCache.sharedInstance().clearExclude(new String[]{Constants.KEY_CURR_SERVER_IP});
        SpUtil.putLong(Constants.KEY_USER_ID, -1);
        SpUtil.putString(Constants.KEY_USER_TOKEN, "");
        FragmentBase.loginUser = loginUserDefault;
        saveLoginUser(loginUserDefault);
        FragmentBase.loginUser = null;
        clearUserToken();
        JPushUtils.getInstance().setAlias("");
    }

    /**
     * 当用户退出登录或者Token过期的时候，清除用户登录凭证
     */
    public static void clearUserToken() {
        FileUtils.deleteFileFromInternalStorage("tokenID");
        new HttpDataLoader(null, null, null).POST(HttpDataReqUrl.URL_POST_LOGOUT, true, new MyHashMap());
    }

    /**
     * 存储当前登录的用户对象
     *
     * @param loginUser
     */
    public static void saveLoginUser(LoginUser loginUser) {
        if (loginUser != null) {
            FileUtils.saveFileToInternalStorage("loginUser", JSON.toJSONString(loginUser));
            FileUtils.saveFileToInternalStorage("tokenID", null != loginUser.getTOKEN() ? loginUser.getTOKEN() : "");
            if (null != loginUser.getUSER()) {
                DBOperateUtils.save(loginUser.getUSER());
            }
        }
    }

    public interface OnGetNetInfoBack {
        void back(LoginUser info);
    }

    public static void getNetLoginUser(final Context context, final OnGetNetInfoBack l) {
        new HttpDataLoader(new HttpDataApi.OnRequestCallback() {
            @Override
            public void onRequestSuccess(String url, ResObj result, boolean isFrmCache) {
                if (result.getCode() == 0) {
                    LoginUser loginUser = (LoginUser) result.getData();
                    if (loginUser != null) {
                        LoginUser loginUser1 = getCachedLoginUser();
                        loginUser1.setUSER(loginUser.getUSER());
                        saveLoginUser(loginUser1);
                        l.back(loginUser1);
                    } else {
                        l.back(getCachedLoginUser());
                    }
                } else {
                    if (context != null) {
                        ToastUtil.getInstance().showToast(context, result.getMsg());
                    }
                    l.back(getCachedLoginUser());
                }
            }

            @Override
            public void onRequestError(String url, int statusCode, String error) {
                l.back(getCachedLoginUser());
                if (context != null) {
                    ToastUtil.getInstance().showToast(context, error);
                }
            }
        }, LoginUser.class, HttpDataRequest.TYPE_OBJECT).POST(HttpDataReqUrl.URL_GET_OWNINFO , true,new MyHashMap());
    }

    /***
     * 判断用户是否已经登录
     *
     * @return
     */
    public static boolean isUserLogin() {
        LoginUser loginUser = getCachedLoginUser();
        if (loginUser == null || loginUser.getUSER() == null ) {
            return false;
        } else {
            String tokenID = SpUtil.getString(Constants.KEY_USER_TOKEN);
            if (TextUtils.isEmpty(tokenID)) {
                return false;
            }
        }
        return true;
    }

    /**
     * 用于超市登录提示框
     *
     * @param context
     * @param message  提示内容
     * @param backType 登录之后的返回状态 0登录之后返回到主页 1登录之后返回之前页面
     */
    public static void showLoginDialog(final Context context, String message, final int backType) {
        if (context == null) {
            return;
        }
        AlertDialog.OnClickListener listener = new AlertDialog.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                switch (which) {
                    case DialogInterface.BUTTON_POSITIVE:
                        UserInfoUtils.clearUserToken();
                        Intent intent = new Intent(context, ActivityLogin.class);
                        intent.putExtra("SKIP_PAGE", backType);//0登录之后返回到主页 1登录之后返回之前页面
                        context.startActivity(intent);
                        break;
                }
            }
        };
        if (StringUtil.isEmpty(message)) {
            message = "需要登录后，才能继续以下操作，是否现在登录？";
        }
        AlertDialog alertDialog = new AlertDialog.Builder(context).setTitle(R.string.tips).setMessage(message).setPositiveButton(R.string.sure, listener).setNegativeButton(R.string.cancel, listener).create();
        alertDialog.setCanceledOnTouchOutside(false);
        alertDialog.show();
    }

    // 退出登录
    public static void loginOut() {
        String userToken = SpUtil.getString(Constants.KEY_USER_TOKEN);
        if (!TextUtils.isEmpty(userToken)) {
            HttpDataLoader dataLoader = new HttpDataLoader(null, null, null);
            dataLoader.POST(HttpDataReqUrl.URL_POST_LOGOUT, true, new MyHashMap());
        }
        clearLoginInfo();
        ActivityBase.closeAllOpenedActivityNoMain();
    }

    public interface OnGetLocationBackListener {
        void onLocationDataBack(LocationDetails locationDetails);
    }

    /**
     * 获取地理位置信息
     */
    public static void getLocation(Context context, final OnGetLocationBackListener l) {
        if (context == null) {
            return;
        }
        if (locationGetter == null) {
            locationGetter = new LocationGetter(context, new OnLocationReceivedListener() {
                @Override
                public void onLocationReceived(final LocationDetails locationDetails, boolean isOverAgagin, AMapLocation amapLocation) {
                    locationGetter.stopLocation();
                    if (locationDetails == null
                            || !StringUtil.isEmpty(locationDetails.getErrorMessage())
                            || !LocationGetter.isValidateLatitude(locationDetails.latitude)) {
                        LogUtils.d(TAG, "地理位置信息获取失败:" + locationDetails.getErrorMessage());
                        final LocationDetails cachedChoosedLocation = (LocationDetails) SecondLevelCache.sharedInstance().get(Constants.KEY_MAIN_LOCATION_CACHE_DATA);
                        if (cachedChoosedLocation != null) {
                            l.onLocationDataBack(cachedChoosedLocation);
                        } else {
                            l.onLocationDataBack(null);
                        }
                        return;
                    }
                    l.onLocationDataBack(locationDetails);
                    LogUtils.d(TAG, "地理位置信息获取成功 ： " + locationDetails);
                    SecondLevelCache.sharedInstance().put(Constants.KEY_MAIN_LOCATION_CACHE_DATA, locationDetails);
                }
            });
            locationGetter.getLocation();
        } else {
            locationGetter.stopLocation();
            locationGetter.getLocation();
        }
    }

    /**
     * 从地理位置信息中获取当前页面的标题
     */
    public static String getTitleFromLocation(LocationDetails locationResult) {
        if (locationResult == null) {
            return "";
        }
        String addrStr = locationResult.getAddrStr();
        String province = locationResult.getProvince();
        String city = locationResult.getCity();
        String district = locationResult.getDistrict();
        String titleTemp = "";
        try {
            titleTemp = addrStr.substring((province + city + district).length()).trim();
        } catch (Exception e) {
        }
        return titleTemp;
    }

    /**
     * 从地理位置信息中获取省市
     */
    public static String getPCFromLocation(LocationDetails locationResult) {
        if (locationResult == null) {
            return "";
        }
        String province = locationResult.getProvince();
        String city = locationResult.getCity();
        String d = locationResult.getDistrict();
        return province + " " + city + " " + d;
    }

}
